package servlet.play;

import com.alibaba.fastjson.JSON;
import pojo.Result;
import pojo.User;
import service.PlayListService;
import service.impl.PlayListServiceImpl;
import utils.JsonUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;
import java.util.stream.Collectors;

@WebServlet("/play/addToPlaylist")
public class AddPlayList extends HttpServlet {
    PlayListService playListService = new PlayListServiceImpl();

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 前端传来的是一个名为songId的列表
        String data = req.getReader().lines().collect(Collectors.joining(System.lineSeparator()));
        User currentUser = (User) req.getSession().getAttribute("user");
        List<Integer> songIdList = JsonUtils.extractSongIdsAsList(data, "songIds");
        Result result = null;
        if (songIdList == null) {
            result = Result.error("参数错误");
        }
        if (playListService.addToPlaylist(currentUser.getUserId(), songIdList)) {
            result = Result.success();
        } else {
            result = Result.error("添加失败");
        }
        String jsonResponse = JSON.toJSONString(result);
        // 将 JSON 字符串作为响应发送给前端
        resp.getWriter().write(jsonResponse);
//        resp.getWriter().close();
//        resp.getWriter().flush();
    }
}
